package com.gao.d_threadpool.d;

import java.util.concurrent.*;

/**
 * @author gaopeng
 * @time 2021/03/18 17:23:04
 */

class MyThreadFactory implements ThreadFactory {
    private static int seed = 0;

    @Override
    public Thread newThread(Runnable r) {
        System.out.println("i am here");
        Thread t = new Thread(r);
        t.setName("Thread(" + seed++ + ")");
        return t;
    }
}

public class App {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(1);
        ThreadPoolExecutor executor =
                new ThreadPoolExecutor(1, 2, 1L, TimeUnit.SECONDS, queue, new MyThreadFactory());

        // 设置是否允许核心线程超时被清除
        executor.allowCoreThreadTimeOut(true);

        for (int i = 1; i <= 3; i++) {
            final int task = i;
            executor.execute(() -> {
                System.out.println(Thread.currentThread().getName() + ": " + task);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 流程走到这里，  线程池里面，肯有2个线程，1个核心，1个非核心

        // 故意停顿2秒，一定会超过 闲置时间
        Thread.sleep(2000L);
        System.out.println("==========================================================================");

        // 流程走到这里，线程池中的线程就已经超时了， 核心的  和 非核心的 线程 都超时了。

        for (int i = 1; i <= 3; i++) {
            final int task = i;
            executor.execute(() -> {
                System.out.println(Thread.currentThread().getName() + ": " + task);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        executor.shutdown();

    }
}
